﻿/*
	Copyright 2009 Intuitive Solutions

	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

	   http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/

using System;
using Gloo.Core.Services;
using System.Windows.Forms;
using mshtml;
using System.Reflection;

namespace Gloo.Services.Automation.Mshtml
{
	public class Service : IService
	{
		protected ServiceContainer scServiceContainer;

		public Service(ServiceContainer scServiceContainer)
		{
			this.scServiceContainer = scServiceContainer;
		}

		public void RegisterServiceListener(Type tService)
		{
			ServiceProviderAttribute spServiceProvider = ((ServiceProviderAttribute[])tService.GetCustomAttributes(typeof(ServiceProviderAttribute), true))[0];
			scServiceContainer.tObjectType = tService;
		}

		public void ExecuteAction(object oObject, string sActionName)
		{
			IHTMLElementCollection hecElementCollection = ((IHTMLDocument2)scServiceContainer.Container.Document.DomDocument).all;
			IHTMLElement heFoundElement = null;

			PropertyInfo[] pia = scServiceContainer.tObjectType.GetProperties();

			for (int i = 0; i < pia.Length; i++)
			{
				if (pia[i].GetCustomAttributes(typeof(ServiceParameterAttribute), true).Length > 0)
				{
					string sControl = ((ServiceParameterAttribute[])pia[i].GetCustomAttributes(typeof(ServiceParameterAttribute), true))[0].ParameterName;

					heFoundElement = (IHTMLElement)hecElementCollection.item(sControl, 0);

					if (heFoundElement != null)
					{
						((HTMLInputElement)heFoundElement).value = (string)pia[i].GetValue(oObject, null);
					}
				}
			}

			MethodInfo[] mia = scServiceContainer.tObjectType.GetMethods();

			for (int i = 0; i < mia.Length; i++)
			{
				if (mia[i].Name.Equals(sActionName) &&
					mia[i].GetCustomAttributes(typeof(ServiceActionAttribute), true).Length > 0)
				{
					string sControl = ((ServiceActionAttribute[])mia[i].GetCustomAttributes(typeof(ServiceActionAttribute), true))[0].ActionName;

					heFoundElement = (IHTMLElement)hecElementCollection.item(sControl, 0);

					if (heFoundElement != null)
					{
						heFoundElement.click();
					}

					break;
				}
			}
		}
	}
}
